<?

	class Pear_auth {
		var $ci;
		var $a;
		var $lib_params;
		var $conf;
		function Pear_auth($lib_params){
			$this->ci =& get_instance();
			$this->ci->load->database();
			$this->ci->load->library('email');
			$this->lib_params = $lib_params;
			
			include("application/config/database.php");
			include("application/config/config.php");
			require_once("pear/Auth/Auth.php");
			require_once("pear/PEAR.php");
			require_once("pear/DB.php");
			require_once("pear/DB/mysql.php");			

			$this->conf = $config;
			
			$dsn = "mysql://".$db['default']['username'].":".$db['default']['password']."@".$db['default']['hostname']."/".$db['default']['database'];
			$params = array("dsn" => $dsn, 
							"table" => $this->lib_params['table'], 
							"usernamecol" => "username", 
							"passwordcol" => "password", 
							"cryptType" => "MD5");
			$this->a = new Auth("DB", $params, "loginFunction", false);
			$this->a->start();
			function loginFunction() {}
		}
		function auth_info () {
			if ($this->a->getUsername() == ""){
				return array("auth" => false, "username" => "");
			}
			return array("auth" => true, "username" => $this->a->getUsername(), "additional" => $this->get_acc_type($this->a->getUsername()));
		}
		function get_acc_type ($login) {
			$this->ci->db->query("UPDATE {$this->lib_params['table']} SET changed=NOW() WHERE username = '$login'");
			
			$query = $this->ci->db->getwhere($this->lib_params['table'], array('username' => $login));
			$res = $query->result_array();
			if ($res[0]['active'] == "0"){
				$this->a->logout();
				$this->a->start();
				redirect('user/index');
				return false;
			}
			else
				return $res;
		}
		function logout () {
			$this->a->logout();
			$this->a->start();
		}
		function change_pass_n_send_email($email){
			$rand_password = $this->fnRandomPassword();
			$this->ci->db->query("UPDATE {$this->lib_params['table']} SET password=MD5('$rand_password') WHERE email = '$email'");
			$this->ci->email->from($this->conf['mail_site_name'], $this->conf['mail_site_email']);
			$this->ci->email->to($email);
			$this->ci->email->subject($this->conf['mail_site_name'].' Password Assistance');
			$this->ci->email->message('Dear Customer,

Your NEW PASSWORD is: '.$rand_password.'

Best regards,
'.$this->conf['mail_site_name'].' Team');
			
			$this->ci->email->send();

			//var_dump($email, $rand_password);
		}
		function fnRandomPassword($var_MaxLength = "8") {
			$var_Password = ""; 
			$var_Possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
			while(($i < $var_MaxLength)&&(strlen($var_Possible) > 0)) { 
				$i++;
				$var_Character = substr($var_Possible, mt_rand(0, strlen($var_Possible)-1), 1);
				$var_Possible = preg_replace("/$var_Character/", "", $var_Possible); 
				$var_Password .= $var_Character;
			}
			return $var_Password;
		}		
	}



?>